/*
 * This packet is a request to log into the system
 *
 * @author Jonathan Walsh (jwalsh8484@gmail.com)
 */

package egs.packets;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;

import java.util.LinkedList;
import java.util.ListIterator;

public class OppListPacket extends Packet {

    short num_opp;
    LinkedList<String> opp_list;
    
    public OppListPacket( short game_name, short game_version, LinkedList<String> opp_list ) throws PacketException {

        /*Set up the header*/
        message_type = MSG_OPP_LIST;
        this.game_name = game_name;
        this.game_version = game_version;
        
        /*fill in the length*/
        num_opp = (short)opp_list.size();
        this.opp_list = opp_list;
        
        /*Verify that usernames are valid length*/
        ListIterator<String> itr = opp_list.listIterator();
        while ( itr.hasNext() ) {
            String next = itr.next();
            if ( next.length() > 30 )
                throw new PacketException( "Invalid length username:" + next );
        }
        
        /*calculate data area*/
        data_area_size = 4 + 30*2*num_opp;
    }
    
    public OppListPacket( byte[] raw ) {
        ByteBuffer buf = setHeaderNew( raw );
        
        num_opp = buf.getShort();
        short empty = buf.getShort();
        
        /*build the user name list*/
        char[] read = new char[30];
        opp_list = new LinkedList<String>();
        for ( int i = 0; i < num_opp; i++ ) {
            for ( int j = 0; j < 30; j++ )
                read[j] = buf.getChar();
            String opp = new String( read );
            opp_list.add( opp.substring(0, opp.indexOf('\0')) );
        }
    }
	
    public byte[] getRaw() {
        ByteBuffer buf = makeBufferWithHeader( data_area_size );
        buf.putShort( num_opp );
        buf.putShort( (short)0 );
        
        /*put in the user name list*/
        int i; String next;
        ListIterator<String> itr = opp_list.listIterator();
        while ( itr.hasNext() ) {
            next = itr.next();
            i = 0;
            for ( ; i < next.length(); i++ )
                buf.putChar( next.charAt( i ) );
            for ( ; i < 30; i++ ) 
                buf.putChar( '\0' );
        }
        
        return buf.array();
    }
    
    
    public String toString() {
        String ret = super.toString() + "\nnum_opp=" + num_opp;
        ret = ret + "\nopp_list=";
        
        ListIterator<String> itr = opp_list.listIterator();
        while ( itr.hasNext() ) ret = ret + "\n  " + itr.next();
        
        return ret;
    }
    
    public short get_num_opp() { return num_opp; }
    public LinkedList<String> get_opp_list() { return opp_list; }
    
}
